package com.hfmall.controller;


import com.hfmall.entity.HfUser;
import com.hfmall.entity.ResponseCode;
import com.hfmall.exception.ServiceException;
import com.hfmall.service.IHfUserService;
import com.hfmall.utils.MailUtils;
import com.hfmall.utils.ResponseState;
import com.hfmall.utils.UuidUtil;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author liclo
 * @author gongkun_pc
 * @since 2021-08-12
 */
@CrossOrigin
@Controller
@RequestMapping("/user")
public class HfUserController {
    @Resource
    private IHfUserService iHfUserService;

    @PostMapping("getUser")
    @ResponseBody
    public ResponseCode<HfUser> getUserBysession(@RequestBody HfUser user){
        if (user==null){
            return new ResponseCode<>(ResponseState.FAIL, "fail");
        }
       HfUser u=iHfUserService.getById(user.getId());
       return new ResponseCode<>(u);
    }

    @ResponseBody
    @PostMapping("resgister")
    public ResponseCode<?> resgister(@RequestBody HfUser user){

        HfUser userz =iHfUserService.getbyName(user.getName());
        if (userz!=null){
           return new ResponseCode<>(ResponseState.FAIL,"账号已存在!");
        }

        user.setGender("B");
        user.setScore(200);
        user.setHead("default_avt.png");
        user.setBirthday("1988-8-8 ");
        user.setStatus("n");
        user.setPaypwd("123456");
        user.setCode(UuidUtil.getUuid());
        iHfUserService.save(user);
        String url="<a href='http://192.168.6.125:8080/user/active?code="+user.getCode()+"'>点击激活汉服商城</a>";
        MailUtils.sendMail(user.getEmail(),url,"激活账号");
        return new ResponseCode<>(ResponseState.SUCCESS);
    }


    @GetMapping("active")
    public String active(String code){
      HfUser user= iHfUserService.findByCode(code);
      if (user!=null) {
          user.setStatus("y");
          iHfUserService.updateById(user);
          return "succeed";
      }else {
          return "Fail";
      }
    }

    @ResponseBody
    @PostMapping("sendMail")
    public ResponseCode sendMail(@RequestBody HfUser user,HttpSession session){
         HfUser userz = iHfUserService.getbyName(user.getName());

        if (userz!=null) {
            int flag=(int)((Math.random()*9+1)*100000);
            String url="验证码为:<h4>"+flag+"<h4>";
            session.setAttribute("code",flag);
            MailUtils.sendMail(userz.getEmail(),url,"验证码");
            return new ResponseCode<>(userz);
        }else {
            return new ResponseCode<>(ResponseState.FAIL,"用户名不存在!");
        }
    }

    private String imagePath="D://gfhf_images";

    @PostMapping("upload")
    public String add(MultipartFile file,int userId) {


        HfUser user = new HfUser();
        user.setId(userId);

        String fileName = "/" + file.getOriginalFilename();
        String filePath = imagePath + fileName;

        File saveDir = new File(filePath);
        if (!saveDir.getParentFile().exists()) {
            saveDir.getParentFile().mkdirs();
        }
        try {
            file.transferTo(saveDir);
        } catch (IOException e) {
            e.printStackTrace();
        }
        user.setHead(fileName);
        iHfUserService.updateById(user);

        return "udai_welcome" ;
    }

    @ResponseBody
    @GetMapping("restartPwd")
    public ResponseCode restartPwd( int userId,String newpwd,Integer code,HttpSession session){
        Integer flag= (Integer) session.getAttribute("code");
        System.out.println(flag);
        System.out.println(code);
        System.out.println(userId);
        HfUser user = new HfUser();
        user.setId(userId);
        user.setPassword(newpwd);
        if (flag.equals(code)){
            iHfUserService.updateById(user);
            return new ResponseCode(ResponseState.SUCCESS);
        }else {

            return new ResponseCode(ResponseState.FAIL,"验证码错误!");
        }
    }

    @GetMapping("login")
    public String login(){
        return "login";
    }

    @GetMapping("logout")
    public String logout(HttpSession session){
        session.removeAttribute("user");
        return "redirect:/user/login";
    }

    @GetMapping("ucenter")
    public String ucenter( String src,Model model){

        if (src==null){
            src = "/uwelcome.html";
        }else {
            src="/"+src+".html";
        }
        model.addAttribute("src",src);
        return "udai_welcome";
    }

    @GetMapping("index")
    public String index(){
        return "main";
    }

    @ResponseBody
    @PostMapping("login")
    public ResponseCode login(@RequestBody HfUser user, HttpSession session) {

        HfUser m = iHfUserService.login(user.getName());
        System.out.println(m);
        if (m == null) {
            return new ResponseCode(403, "用户名不存在!");
        } else {
            if (!m.getStatus().equals("y")){
                return new ResponseCode(403, "账号未激活!");
            }else if (!m.getPassword().equals(user.getPassword())) {
                return new ResponseCode(405, "密码不正确!");
            } else {
                session.setAttribute("user",m);
                //TODO 产生JWT
                /*String jwt = JwtUtil.createJWT(m.getId(), m.getAccount(), audience);
                response.addHeader("jwt", jwt);*/
                return new ResponseCode(m);
            }
        }
    }

    @ResponseBody
    @PostMapping("update")
    public ResponseCode<?> updateUser(@RequestBody HfUser user){
        try {
            iHfUserService.updateById(user);
            return new ResponseCode<>(ResponseState.SUCCESS);
        }catch(ServiceException e){
            return new ResponseCode<>(ResponseState.FAIL, "fail");
        }

    }
    @ResponseBody
    @GetMapping("list")
    public ResponseCode<List<HfUser>> list(){
        return new ResponseCode<List<HfUser>>(iHfUserService.list());
    }
    @ResponseBody
    @PostMapping("updates")
    public ResponseCode update(@RequestBody HfUser user){
        iHfUserService.updateByID(user);
        return ResponseCode.SUCCESS;
    }
    @ResponseBody
    @GetMapping("del")
    public ResponseCode del(int id){
        iHfUserService.removeById(id);
        return ResponseCode.SUCCESS;
    }
}
